import React, { PureComponent } from 'react'
const AContext = React.createContext()
export default class ContextDemo extends PureComponent {
  state = {
    username: 'Jack'
  }
  render() {
    return (
      <div style={{background:'pink', width: 600+'px'}}>
        <h1>A组件-爷</h1>
        <h3>用户名：{this.state.username}</h3>
        <AContext.Provider value={this.state.username}>
          <B/>
        </AContext.Provider>
      </div>
    )
  }
}

class B extends PureComponent {
  // B也可以用context获取 但是应该用props
  // static contextType = AContext
  state = {
    username: 'Jack'
  }
  render() {
    return (
      <div style={{background:'skyblue', width: 400+'px'}}>
        <h1>B组件-父</h1>
        {/* <h3>从A组件获取到的用户名：{this.context}</h3> */}
        <C/>
      </div>
    )
  }
}

class C extends PureComponent {
  // 声明接收context
  static contextType = AContext
  state = {
    username: 'Jack'
  }
  render() {
    return (
      <div style={{background:'yellow', width: 200+'px'}}>
        <h1>C组件-孙</h1>
        <h3>从A组件获取到的用户名：{this.context}</h3>
        <D/>
      </div>
    )
  }
}

function D() {
  return (
    <div>
      <h6 style={{background:'red', width: 100+'px'}}>D组件-祖孙
        <AContext.Consumer>
          {
            value => <span>获取到的值是：{value}</span>
          }
        </AContext.Consumer>
      </h6>
    </div>
  )
}